package com.yuand.filter;

import com.alibaba.fastjson.JSON;
import com.yuand.core.RedisCache;
import com.yuand.entity.LoginUser;
import com.yuand.utils.JwtUtils;
import com.yuand.utils.ResponseResult;
import com.yuand.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @ClassName: JwtAuthenticationTokenFilter
 * @Author: yuandong
 * @Date 2022/1/14 15:48
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        log.info("进入JwtAuthenticationToken过滤器");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userId = JwtUtils.getUserId(token);
        if(!StringUtils.hasText(userId)){
            ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"token错误,重新登录~~~");
            String json = JSON.toJSONString(result);
            //处理异常
            WebUtil.renderString(response,json);
            return;
        }

        boolean verify = JwtUtils.verify(token, userId);
        if(!verify){
            ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(),"token失效，请重新登录"); //401
            String json = JSON.toJSONString(result);
            //处理异常
            WebUtil.renderString(response,json);
            return;
        }

        //从redis中获取用户信息
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){

            ResponseResult result = new ResponseResult(HttpStatus.NOT_FOUND.value(),"用户不存在");
            String json = JSON.toJSONString(result);
            //处理异常
            WebUtil.renderString(response,json);
        }
        //存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }

}
